package com.lt.integration.qywx.auth;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.lt.integration.qywx.constant.QyUrlConstant;
import com.lt.integration.qywx.constant.QyWxConstant;
import com.lt.integration.qywx.entity.*;
import com.lt.integration.qywx.util.AuthUtil;
import com.lt.integration.qywx.weixin.AesException;
import com.lt.integration.qywx.weixin.WXBizMsgCrypt;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 企业微信公共服务
 * @ author     :  Dragon
 * @ Created in :  2021年05月14日 11:26
 */
@Slf4j
public class QyWeiXinAccount {

    /**
     * 常量参数
     */
    private WxCorpConfig config;


    public static void main(String[] args) {
        WxCorpConfig config = new WxCorpConfig();
        config.setSuiteId("ww82db44424e4611dc");
        config.setSuiteSecret("VcFiuFMQdYHEYcCS65MNaU0U7ELLboj8yipN6GtPGrM");
        config.setSuiteTicket("3Q9MvzT69nQD2OGcckI6gz_EtgCNtevz-l2OHK_Fxdk8lJMMAZq6QP-2jajdiga1");

        config.setCorpId("ww27d6dbd1a8325e85");
        config.setCorpSecret("Atj9BNl4bExg9XL9iZmTa5ybVS1-12CKOgQXP2gy8Jg");
        config.setPermanentCode("1KIWJV5BtDixDCqUI0j2aY6wVjZ3ETON5WF3VuqO_Ps");
        config.setAgentId("1000250");

//        config.setCorpId("ww4bf13e3dca64b920");
//        config.setCorpSecret("HfLw_9OA1Hiyzia_IIkL63SujAbsohlxxvf_yj_2RyM");
//        config.setPermanentCode("OjyOdICpWB84PZtDGEUfpLxdNeGssKA61ZnsmRX_-oQ");
//        config.setAgentId("1000027");

        QyWeiXinAccount account = new QyWeiXinAccount(config);

//        String corpToken = account.getCorpToken();
//        System.out.println("corpToken: " + corpToken);
//        String corpAccessToken = account.getCorpAccessToken();
//        System.out.println("corpAccessToken: " + corpAccessToken);
//
//        JSONObject wxUser = account.getWxUser("LongZhangYin");
//        System.out.println("wxUser: " + wxUser);

//        List<WxCorpDept> corpDepts = account.getDepartmentList("");
//        System.out.println("corpDepts: " + corpDepts);

//        List<WxCorpUser> users = account.getDepartmentUserList("1", "1");
//        System.out.println("users: " + users);
//        String tousers = users.stream().map(WxCorpUser::getUserid).collect(Collectors.joining("|"));
//        System.out.println("tousers: " + tousers);
//        String content = "测试群发消息";
//        account.send(null, null, null, content);
    }


    /**
     * 构造函数
     */
    public QyWeiXinAccount(WxCorpConfig config){
        this.config = config;
    }

    /**
     * 企业微信授权登录
     * @param code
     */
//    public BrandWxBindDTO loginByMiniAppCode(String code) throws WeixinException {
//        BrandWxBindDTO dto = getWxUserInfo(code);
//        return dto;
//    }


    /**
     * 应用验证回调URL有效性
     * @author:leap
     * @MethodName: verifyURL
     * @Description:
     * @param msgSignature url中的签名
     * @param timestamp url中的时间戳
     * @param nonce url中的随机字符串
     * @param echostr 回显字符串
     * @param corpid 用于创建解密类
     * @return 返回解密后的明文字符串
     * @throws AesException
     * @date:2016年8月30日
     */
    public String verifyURL(String msgSignature, String timestamp, String nonce, String echostr, String corpid, String token, String aesKey) throws AesException {
        //注意创建解密对象时使用的是CORP_ID而不是SUITE_ID
        WXBizMsgCrypt wxBizMsgCrypt = new WXBizMsgCrypt(token, aesKey, corpid);
        String result = wxBizMsgCrypt.VerifyURL(msgSignature, timestamp, nonce, echostr);
        return result;
    }


    /**
     * 获取suite_access_token
     * @param suiteId 应用id
     * @param secret  应用秘钥
     * @param suiteTicket   suite_ticket由企业微信后台定时推送给 suite_ticket实际有效期为30分钟
     * @return
     */
    public String getSuiteAccessToken(String suiteId, String secret, String suiteTicket){
        String tokenUrl = QyUrlConstant.WX_SUITE_TOKEN_URL;
        JSONObject obj = new JSONObject();
        obj.element("suite_id", suiteId);
        obj.element("suite_secret", secret);
        obj.element("suite_ticket", suiteTicket);
        JSONObject jsonObject = AuthUtil.doPostJson(tokenUrl, obj.toString());
//        log.info("【获取suite_access_token】,suite_access_token  = {}", jsonObject);
        String access_token = jsonObject.get("suite_access_token").toString();
        return access_token;
    }

    /**
     * 获取永久授权码
     * @return
     */
    public WxCorpPermanentCode getPermanentCode(String authCode) {
        String url = QyUrlConstant.PERMANENT_CODE_URL.replace("SUITE_ACCESS_TOKEN", getSuiteAccessToken(config.getSuiteId(), config.getSuiteSecret(), config.getSuiteTicket()));
        JSONObject object = new JSONObject();
        object.element("auth_code", authCode);
        JSONObject jsonObject = AuthUtil.doPostJson(url, object.toString());
//        log.info("============== jsonObject : " + jsonObject);
        if (null == jsonObject.get("permanent_code")){
            return null;
        }
        // 获取授权码
        String permanentCode = jsonObject.get("permanent_code").toString();
        // 授权企业消息
        String auth_corp_info = jsonObject.get("auth_corp_info").toString();
        JSONObject auth_corp_info_obj = JSONObject.fromObject(auth_corp_info);
        String auth_corpid = auth_corp_info_obj.get("corpid").toString();
        String auth_corp_name = auth_corp_info_obj.get("corp_name").toString();
        // 安装应用信息
        String auth_info = jsonObject.get("auth_info").toString();
        JSONObject auth_info_obj = JSONObject.fromObject(auth_info);
        // 授权的应用信息，注意是一个数组，但仅旧的多应用套件授权时会返回多个agent，对新的单应用授权，永远只返回一个agent
        List<JSONObject> agent = (List<JSONObject>) auth_info_obj.get("agent");
        log.info("授权的应用信息: " + agent);
        JSONObject agent_obj = agent.get(0);
        String agentId = agent_obj.get("agentid").toString();
        String agentName = agent_obj.get("name").toString();
        // 用户信息
        String auth_user_info = jsonObject.get("auth_user_info").toString();
        JSONObject auth_user_info_obj = JSONObject.fromObject(auth_user_info);
        String userId = auth_user_info_obj.get("userid").toString();
        String userName = auth_user_info_obj.get("name").toString();
        String openUserId = auth_user_info_obj.get("open_userid").toString();

        WxCorpPermanentCode code = new WxCorpPermanentCode();
        code.setCorpId(auth_corpid);
        code.setCorpName(auth_corp_name);
        code.setPermanentCode(permanentCode);
        code.setAgentId(agentId);
        code.setAgentName(agentName);
        code.setUserId(userId);
        code.setUserName(userName);
        code.setOpenUserId(openUserId);
        return code;
    }

    /**
     * 获取企业 token
     * @return
     */
    public String getCorpToken() {
        String suiteAccessToken = getSuiteAccessToken(config.getSuiteId(), config.getSuiteSecret(), config.getSuiteTicket());
        String corp_token_url = QyUrlConstant.CORP_TOKEN_URL.replace("SUITE_ACCESS_TOKEN", suiteAccessToken);
        JSONObject object = new JSONObject();
        object.element("auth_corpid", config.getCorpId());
        object.element("permanent_code", config.getPermanentCode());
        JSONObject jsonObject = AuthUtil.doPostJson(corp_token_url, object.toString());
        String access_token = jsonObject.get("access_token").toString();
        log.info("获取企业 token : {}", access_token);
        return access_token;
    }

    /**
     * 获取内部企业 token
     * @return
     */
    public String getCorpAccessToken() {
        try {
            String corpTokenUrl = QyUrlConstant.WX_ACCESS_TOKEN_URL.replace("CORPID", config.getCorpId()).replace("CORPSECRET", config.getCorpSecret());
            JSONObject accessTokenObj = AuthUtil.doGetJson(corpTokenUrl);
            log.info("【获取内部企业 token】,accessTokenObj  = {}", accessTokenObj);
            String access_token = accessTokenObj.get("access_token").toString();
            log.info("获取内部企业 token : {}", access_token);
            return access_token;
        } catch (Exception e){
            log.error("获取内部企业 token 错误日志：{}", e.getMessage());
        }
        return null;
    }

    /**
     * 微信前端向服务器获取code
     * @param response
     * @return
     * @throws IOException
     */
    public void getCorpCode(HttpServletResponse response, String redirectUrl) {
        try {
            String url = QyUrlConstant.CODE_URL
                    .replace("APPID", config.getSuiteId())
                    .replace("REDIRECT_URI", redirectUrl)
                    .replace("SCOPE", QyWxConstant.WX_SNSAPI_USERINFO)
                    .replace("STATE", QyWxConstant.WX_STATE);
            response.sendRedirect(url);
            log.info("============== 微信前端向服务器获取code: {}", url);
//            return "redirect:" + url;//必须重定向，否则不能成功
        } catch (IOException e){
            log.error("微信前端向服务器获取code错误日志：{}", e.getMessage());
        }
    }

    /**
     * 获取访问用户身份
     */
    public WxCorpUserInfo getWxUserInfo(String code){
        try {
            String accessToken = getSuiteAccessToken(config.getSuiteId(), config.getSuiteSecret(), config.getSuiteTicket());
            //拼装获取访问用户身份的userid的url请求
            log.info("【accessToken】: {}", accessToken);
            log.info("【code】: {}", code);
            String useridURL = QyUrlConstant.WX_USERID_URL.replace("SUITE_ACCESS_TOKEN", accessToken).replace("CODE", code);
            //获取访问用户身份的基本信息（如userid）
            JSONObject object = AuthUtil.doGetJson(useridURL);
            log.info("【访问用户身份基本信息】,obj  = {}", object);
            String corpId = object.get("CorpId").toString();
            String userId = object.get("UserId").toString();
            String DeviceId = object.get("DeviceId").toString();
            String user_ticket = object.get("user_ticket").toString();
            String expires_in = object.get("expires_in").toString();

            String openUserId = object.get("open_userid").toString();
//            WxCorpUser wxUser = getWxUser(userId);
//            log.info("【头像消息】,avatar  = {}", wxUser.getAvatar());
//            String avatar = wxUser == null ? "" : wxUser.getAvatar().replace("http", "https");
//            if (6 == avatar.length()){
//                avatar = avatar.substring(0, 5);
//            }
            WxCorpUserInfo user = new WxCorpUserInfo(corpId, userId, DeviceId, user_ticket, expires_in, openUserId, null);
            return user;
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 转换userId
     * @param userId
     * @return
     */
    public JSONObject wxUserId(String userId){
        String corpToken = getCorpToken();
        String url = QyUrlConstant.USER_ID_URL.replace("ACCESS_TOKEN", corpToken);
        JSONObject object = new JSONObject();
        List<String> userArr = new ArrayList<>();
        userArr.add(userId);
        object.element("userid_list", userArr);
        JSONObject jsonObject = AuthUtil.doPostJson(url, object.toString());
        log.info("【获取微信userId】,obj  = {}", jsonObject);
        if (null == jsonObject){
            log.error("转换微信userId错误");
            return null;
        }
        List<JSONObject> openUseridList = (List<JSONObject>) jsonObject.get("open_userid_list");
        if (0 >= openUseridList.size()){
            log.error("转换微信userId错误");
            return null;
        }
        JSONObject userObj = openUseridList.get(0);
        return userObj;
    }


    /**
     * 通过手机号获取企业userId 校验是否是当前userId 匹配
     */
    public Boolean verifyCorpUserId(String mobile, String userId){
        log.info("=============== userid: {}", userId);
        Boolean isCorpUserId = true;
        String url = QyUrlConstant.USER_ID_URL.replace("ACCESS_TOKEN", getCorpAccessToken());
        JSONObject object = new JSONObject();
        object.element("mobile", mobile);
        JSONObject jsonObject = AuthUtil.doPostJson(url, object.toString());
        log.info("【通过手机号获取企业userId】 jsonObject = {}", jsonObject);
        if (jsonObject.has("userid")) {
            String corpUserId = jsonObject.get("userid").toString();
            if (!userId.equals(corpUserId)){
                JSONObject userJson = wxUserId(userId);
                String openUserid = userJson.get("open_userid").toString();
                if (userId.equals(openUserid)){
                    isCorpUserId = false;
                }
            } else {
                isCorpUserId = false;
            }
        }
        return isCorpUserId;
    }

    /**
     * 获取企业微信成员数据
     * @return
     */
    public WxCorpUser getWxUser(String wxUserId){
        try {
//            JSONObject userJson = wxUserId(wxUserId);
//            log.info("=============请求URL: {}", userJson);
//            String userId = userJson.get("userid").toString();
            //拼装获取访问用户身份的userid的url请求
            String corpToken = getCorpAccessToken();
            String userInfoURL = QyUrlConstant.WX_USERINFO_URL.replace("ACCESS_TOKEN", corpToken).replace("USERID", wxUserId);
            JSONObject userObj = AuthUtil.doGetJson(userInfoURL);
            log.info("【访问用户身份明细信息】,userObj  = {}", userObj);
            WxCorpUser wxCorpUser = (WxCorpUser) ConvertUtils.convert(userObj, WxCorpUser.class);
            return wxCorpUser;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取部门列表
     */
    public List<WxCorpDept> getDepartmentList(){
        try {
            String corpToken = getCorpAccessToken();
            String url = QyUrlConstant.DEPARTMENT_LIST_URL.replace("ACCESS_TOKEN", corpToken).replace("ID", "");
            JSONObject object = AuthUtil.doGetJson(url);
            log.info("部门: {}", object);
            Object obj = object.get("department");
            List<WxCorpDept> list = JSONArray.parseArray(obj.toString(), WxCorpDept.class);
            return list;
        } catch (Exception e) {
            log.error("获取部门列表错误日志: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取部门详情
     * @param deptId
     */
    public WxCorpDept getDepartment(String deptId){
        try {
            String corpToken = getCorpAccessToken();
            String url = QyUrlConstant.DEPARTMENT_LIST_URL.replace("ACCESS_TOKEN", corpToken).replace("ID", deptId);
            JSONObject object = AuthUtil.doGetJson(url);
            log.info("部门: {}", object);
            Object obj = object.get("department");
            List<WxCorpDept> list = JSONArray.parseArray(obj.toString(), WxCorpDept.class);
            if (null != list && 0 < list.stream().count()) {
                return list.get(0);
            } else {
                return null;
            }
        } catch (Exception e) {
            log.error("获取部门列表错误日志: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 获取部门成员列表
     * @param deptId      调用接口凭证
     * @param fetchChild  1/0：是否递归获取子部门下面的成员
     */
    public List<WxCorpUser> getDepartmentUserList(String deptId, String fetchChild){
        try {
            String corpToken = getCorpAccessToken();
            String url = QyUrlConstant.DEPARTMENT_USER_LIST_URL.replace("ACCESS_TOKEN", corpToken).replace("DEPARTMENT_ID", deptId).replace("FETCH_CHILD", fetchChild);
            JSONObject object = AuthUtil.doGetJson(url);
            log.info("部门成员: {}", object);
            System.out.println(object);
            Object obj = object.get("userlist");
//            List<WxCorpUser> list = JSON.obj2pojo(obj, List.class);
            List<WxCorpUser> list = JSONArray.parseArray(obj.toString(), WxCorpUser.class);
            return list;
        } catch (Exception e) {
            log.error("获取部门成员列表错误日志: {}", e.getMessage());
        }
        return null;
    }

    /**
     * 发送应用文本消息
     * @param touser   指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为"@all"，则向该企业应用的全部成员发送
     * @param toparty  指定接收消息的部门，部门ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为"@all"时忽略本参数
     * @param totag    指定接收消息的标签，标签ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为"@all"时忽略本参数
     * @param content  消息内容，最长不超过2048个字节，超过将截断（支持id转译）
     * @return
     */
    public JSONObject sendText(String touser, String toparty, String totag, String content){
        String corpAccessToken = getCorpToken ();
        String url = QyUrlConstant.APPLICATION_MESSAGE_SEND_URL.replace("ACCESS_TOKEN", corpAccessToken) + "&debug=1";
        JSONObject obj = new JSONObject();
        JSONObject textObj = new JSONObject();
        textObj.element("content", content);
        obj.element("touser", touser);
        obj.element("toparty", toparty);
        obj.element("totag", totag);
        obj.element("msgtype", "text");
        obj.element("agentid", config.getAgentId());
        obj.element("text", textObj);
        obj.element("safe", 0);
        obj.element("enable_id_trans", 0);
        obj.element("enable_duplicate_check", 0);
        obj.element("duplicate_check_interval", 1800);
        log.info("发送消息：" + textObj.toString());
        JSONObject jsonObject = AuthUtil.doPostJson(url, obj.toString());
        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("创建成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        log.info("发送结果：" + JSON.toJSONString(jsonObject));
//        String errcode = jsonObject.get("errcode").toString();
        return jsonObject;
    }

    /**
     * 发送应用文本卡片消息
     * @param touser   指定接收消息的成员，成员ID列表（多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为"@all"，则向该企业应用的全部成员发送
     * @param toparty  指定接收消息的部门，部门ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为"@all"时忽略本参数
     * @param totag    指定接收消息的标签，标签ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为"@all"时忽略本参数
     * @param title   标题，不超过128个字节，超过会自动截断（支持id转译）
     * @param description  	描述，不超过512个字节，超过会自动截断（支持id转译）
     * @param jumpUrl  点击后跳转的链接。最长2048字节，请确保包含了协议头(http/https)
     * @param btntxt  按钮文字。 默认为“详情”， 不超过4个文字，超过自动截断。
     * @return
     */
    public JSONObject sendTextCard(String touser, String toparty, String totag, String title, String description, String jumpUrl, String btntxt){
        String corpAccessToken = getCorpToken ();
        String url = QyUrlConstant.APPLICATION_MESSAGE_SEND_URL.replace("ACCESS_TOKEN", corpAccessToken) + "&debug=1";
        JSONObject obj = new JSONObject();
        JSONObject textObj = new JSONObject();
        textObj.element("title", title);
        textObj.element("description", description);
        textObj.element("url", jumpUrl);
        textObj.element("btntxt", btntxt == null || "".equals(btntxt) ? "详情" : btntxt);

        obj.element("touser", touser);
        obj.element("toparty", toparty);
        obj.element("totag", totag);
        obj.element("msgtype", "textcard");
        obj.element("agentid", config.getAgentId());
        obj.element("textcard", textObj);
        obj.element("safe", 0);
        obj.element("enable_id_trans", 0);
        obj.element("enable_duplicate_check", 0);
        obj.element("duplicate_check_interval", 1800);
        log.info("发送消息：" + textObj.toString());
        JSONObject jsonObject = AuthUtil.doPostJson(url, obj.toString());
        //4.错误消息处理
        if (null != jsonObject) {
            if (0 != jsonObject.getInt("errcode")) {
                log.error("创建成员失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
            }
        }
        log.info("发送结果：" + JSON.toJSONString(jsonObject));
        return jsonObject;
    }

    /**
     * 获取员工打卡规则
     * @param datetime   需要获取规则的日期当天0点的Unix时间戳
     * @param userIdList 需要获取打卡规则的用户列表
     */
    public void getcheckinoption(Integer datetime, List<String> userIdList){
        String corpAccessToken = getCorpAccessToken();
        String url = QyUrlConstant.CHECKINOPTION_URL.replace("ACCESS_TOKEN", corpAccessToken);
        JSONObject obj = new JSONObject();
        obj.element("datetime", datetime);
        obj.element("useridlist", userIdList);
        JSONObject object = AuthUtil.doPostJson(url, String.valueOf(obj));
        log.info("获取员工打卡规则 object: {}", object);
    }


//    /**
//     * 获取访问用户敏感信息
//     */
//    public JSONObject getUserDetail3rd(String userTicket){
//        try {
//            String accessToken = getSuiteAccessToken();
//            //拼装获取访问用户身份的userid的url请求
//            String userDetail3rdURL = platformConfigService.getUserDetail3rd().replace("SUITE_ACCESS_TOKEN", accessToken);
//            //获取访问用户身份的基本信息（如userid）
//            JSONObject object = new JSONObject();
//            object.element("user_ticket", userTicket);
//            JSONObject jsonObject = AuthUtil.doPostJson(userDetail3rdURL, object.toString());
//            log.info("【访问用户身份基本信息】,obj  = {}", jsonObject);
//            return  jsonObject;
//        } catch (Exception e) {
////            e.printStackTrace();
//            log.error(e.getMessage());
//            throw new LoginException("获取企业微信用户错误");
//        }
//    }
//
//    /**
//     * 校验员工手机号是否存在
//     * @param openUserId
//     * @param corpId
//     * @param userId
//     * @return
//     */
//    public WxBindDTO verifyMobile(String openUserId, String corpId, String userId, String avatar){
//        WxBindDTO dto = new WxBindDTO();
//        SysUserQO qo = new SysUserQO();
//        qo.setDelFlag(SysUser.STATUS_NORMAL);
//        qo.setWxOpenUserId(openUserId);
//        qo.setWxCorpId(corpId);
//        SysUser sysUser = sysUserService.queryUnique(qo);
//        if (null == sysUser){
//            dto.setCorpId(corpId);
//            dto.setCorpUserId(userId);
//            dto.setCorpOpenUserId(openUserId);
//            dto.setIsBindMobile(false);
//        } else {
//            dto.setCorpId(corpId);
//            dto.setCorpUserId(userId);
//            dto.setCorpOpenUserId(openUserId);
//            dto.setIsBindMobile(true);
//            if (null == sysUser.getAvatar() || "".equals(sysUser.getAvatar())) {
//                log.info("【更新用户头像】,avatar  = {}", avatar);
//                sysUser.setAvatar(avatar);
//                sysUserService.update(sysUser);
//            }
//        }
//        dto.setAvatar(avatar);
//        return dto;
//    }
//
//    /**
//     * 获取员工
//     * @param openUserId
//     * @param corpId
//     * @param userId
//     * @return
//     */
//    public SysUser getStaff(String mobile, String openUserId, String corpId, String userId, String avatar){
//        if (null != mobile) {
//            Boolean isCorpUserId = verifyCorpUserId(mobile, userId, corpId);
//            if (isCorpUserId) {
//                throw new LoginException(LoginException.CORP_MOBILE_NOT_FOUND);
//            }
//        }
//        SysUserQO qo = new SysUserQO();
//        qo.setDelFlag(SysUser.STATUS_NORMAL);
//        if (null != mobile){
//            qo.setMobile(mobile);
//        } else {
//            qo.setWxOpenUserId(openUserId);
//        }
////        qo.setWxCorpId(corpId);
//        SysUser user = sysUserService.queryUnique(qo);
//        if (null == user){
//            throw new LoginException(LoginException.MOBILE_BIND_NOT_FOUND);
//        } else {
//            if (null == user.getAvatar() || "".equals(user.getAvatar())) {
//                log.info("【更新用户头像】,avatar  = {}", avatar);
//                user.setAvatar(avatar);
//            }
//            user.setWxCorpId(corpId);
//            user.setWxOpenUserId(openUserId);
//            user.setWxUserId(userId);
//            user.setUpdateTime(new Date());
//            sysUserService.update(user);
//        }
//        return user;
//    }
//
//    /**
//     * 获取企业微信 JS_SDK 参数
//     * @param corpId
//     * @return
//     */
//    public Map<String, Object> getCorpJsSdkConfig(String corpId, String url){
//        try {
//            String jsapiTicketUrl = platformConfigService.getJsapiTicketUrl().replace("ACCESS_TOKEN", getCorpAccessToken(corpId));
//            JSONObject jsapiTicketObject = AuthUtil.doGetJson(jsapiTicketUrl);
//            Map<String, Object> map = new HashMap<String, Object>();
//            String ticket = String.valueOf(jsapiTicketObject.get("ticket"));
//            String noncestr = UUIDUtils.uuid().replace("-", "").substring(0, 16);
//            String timestamp = String.valueOf(System.currentTimeMillis()/1000);
//            String str = "jsapi_ticket=JSAPITICKET&noncestr=NONCESTR&timestamp=TIMESTAMP&url=URL"
//                    .replace("JSAPITICKET", ticket)
//                    .replace("NONCESTR", noncestr).replace("TIMESTAMP", timestamp).replace("URL", url);
//            System.out.println("======" + str);
//
//            MessageDigest digest = MessageDigest.getInstance("SHA-1");
//            digest.update(str.getBytes());
//            byte[] messageDigest = digest.digest();
//            StringBuffer hexString = new StringBuffer();
//            for (int i = 0; i < messageDigest.length; i++) {
//                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
//                if (shaHex.length() < 2) {
//                    hexString.append(0);
//                }
//                hexString.append(shaHex);
//            }
//            map.put("appId", corpId);
//            map.put("timestamp", Integer.valueOf(timestamp));
//            map.put("nonceStr", noncestr);
//            map.put("signature", hexString.toString());
//            return map;
//        } catch (Exception e) {
//            e.printStackTrace();
////            log.error(e.getMessage());
//        }
//        return null;
//    }

//    /**
//     * 获取企业微信员工手机号
//     * @param auth_code
//     * @return
//     */
//    public String getCorpStaffMobile(String auth_code) {
//        try {
//            String config = platformConfigService.getApplicationConfig();
//            WxApplicationConfigDTO applicationConfig = ConvertUtils.convert(JSONObject.fromObject(config), WxApplicationConfigDTO.class);
//
//            String providerTokenUrl = platformConfigService.getProviderTokenUrl();
//            JSONObject object = new JSONObject();
//            object.element("corpid", applicationConfig.getCorp_id());
//            object.element("provider_secret", applicationConfig.getCorp_provider_secret());
//            JSONObject corpObj = AuthUtil.doPostJson(providerTokenUrl, object.toString());
//            log.info("【获取corpObj】,corpObj  = {}", corpObj);
//            String provider_access_token = corpObj.get("provider_access_token").toString();
//
//            String userInfoUrl = platformConfigService.getProviderUserinfoUrl().replace("PROVIDER_ACCESS_TOKEN", provider_access_token);
//            JSONObject jsonObjectUser = new JSONObject();
//            jsonObjectUser.element("auth_code", auth_code);
//            JSONObject userInfoObj = AuthUtil.doPostJson(userInfoUrl, jsonObjectUser.toString());
//            log.info("【获取userInfo】, userInfoObj = {}", userInfoObj);
//
//            String user_info_str = userInfoObj.get("user_info").toString();
//            JSONObject user_info_obj = JSON.parseObject(user_info_str, JSONObject.class);
//            String userId = user_info_obj.get("userid").toString();
//            String corp_info_str = userInfoObj.get("corp_info").toString();
//            JSONObject corp_info_obj = JSON.parseObject(corp_info_str, JSONObject.class);
//            String corpId = corp_info_obj.get("corpid").toString();
//
//            //拼装获取访问用户身份的userid的url请求
//            String userInfoURL = platformConfigService.getUserinfoUrl().replace("ACCESS_TOKEN", getCorpAccessToken(corpId)).replace("USERID", userId);
//            JSONObject userObj = AuthUtil.doGetJson(userInfoURL);
//            log.info("【访问用户身份明细信息】,userObj  = {}", userObj);
//            return userObj.get("mobile").toString();
//        } catch (Exception e) {
//            log.error(e.getMessage());
//            throw new LoginException(LoginException.STAFF_ERROR);
//        }
//    }
}
